package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.TemplateDownUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.UserInfoXiaoyu;
import com.ruoyi.system.domain.UserInfoXiongan;
import com.ruoyi.system.service.IUserInfoXionganService;

import javax.servlet.http.HttpServletResponse;

/**
 * 雄安协同平台用户信息Controller
 *
 * @author tjec
 * @date 2021-01-28
 */
@RestController
@RequestMapping("/system/xiongan")
public class UserInfoXionganController extends BaseController
{
    @Autowired
    private IUserInfoXionganService userInfoXionganService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询雄安协同平台用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:xiongan:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserInfoXiongan userInfoXiongan)
    {
        startPage();
        List<UserInfoXiongan> list = userInfoXionganService.selectUserInfoXionganList(userInfoXiongan);
        return getDataTable(list);
    }

    /**
     * 导出雄安协同平台用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:xiongan:export')")
    @Log(title = "雄安协同平台用户信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(UserInfoXiongan userInfoXiongan)
    {
        List<UserInfoXiongan> list = userInfoXionganService.selectUserInfoXionganList(userInfoXiongan);
        ExcelUtil<UserInfoXiongan> util = new ExcelUtil<UserInfoXiongan>(UserInfoXiongan.class);
        return util.exportExcel(list, "xiongan");
    }

    /**
     * 获取雄安协同平台用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:xiongan:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        return AjaxResult.success(userInfoXionganService.selectUserInfoXionganByGuid(guid));
    }

    /**
     * 新增雄安协同平台用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:xiongan:add')")
    @Log(title = "雄安协同平台用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserInfoXiongan userInfoXiongan)
    {
        return toAjax(userInfoXionganService.insertUserInfoXiongan(userInfoXiongan));
    }

    /**
     * 修改雄安协同平台用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:xiongan:edit')")
    @Log(title = "雄安协同平台用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserInfoXiongan userInfoXiongan)
    {
        return toAjax(userInfoXionganService.updateUserInfoXiongan(userInfoXiongan));
    }

    /**
     * 删除雄安协同平台用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:xiongan:remove')")
    @Log(title = "雄安协同平台用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids)
    {
        return toAjax(userInfoXionganService.deleteUserInfoXionganByGuids(guids));
    }

    @Log(title = "雄安协同平台用户信息", businessType = BusinessType.IMPORT)
    // @PreAuthorize("@ss.hasPermi('system:xiaoyu:import')")
     @PostMapping("/importData")
     public AjaxResult importData(MultipartFile file) throws Exception {
         ExcelUtil<UserInfoXiongan> util = new ExcelUtil<UserInfoXiongan>(UserInfoXiongan.class);
         List<UserInfoXiongan> userInfoXionganList = util.importExcel(file.getInputStream());
         LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
         String operName = loginUser.getUser().getUserId();
         String message = userInfoXionganService.importUser(userInfoXionganList, operName);
         return AjaxResult.success(message);
     }

    @Log(title = "雄安协同平台用户信息", businessType = BusinessType.IMPORT)
    // @PreAuthorize("@ss.hasPermi('system:xiaoyu:import')")
     @PostMapping("/importDataOutMember")
     public AjaxResult importDataOutMember(MultipartFile file) throws Exception {
         ExcelUtil<UserInfoXiongan> util = new ExcelUtil<UserInfoXiongan>(UserInfoXiongan.class);
         List<UserInfoXiongan> userInfoXionganList = util.importExcel(file.getInputStream());
         LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
         String operName = loginUser.getUser().getUserId();
         String message = userInfoXionganService.importOutMemberUser(userInfoXionganList, operName);
         return AjaxResult.success(message);
     }

    @Log(title = "雄安协同平台用户模板下载", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:xiongan:down')")
    @GetMapping("/templateDown")
    public void templateDown() throws Exception {
        XSSFWorkbook xssfWorkbook = TemplateDownUtils.getXSSFWorkbook(this, "雄安协同平台内外部.xlsx");
        try {
            String filePass = TemplateDownUtils.createTempFile("雄安协同平台内外部"+ DateUtils.getDate() +".xlsx");
            logger.info("===创建的文件地址=="+filePass);
            //操作流，写入文件内容（根据前端传参）
            File tempFile = new File(filePass);
            tempFile.setExecutable(true);
            tempFile.setReadable(true);
            tempFile.setWritable(true);
            FileOutputStream outStream = new FileOutputStream(tempFile);
            xssfWorkbook.write(outStream);
            outStream.flush();
            outStream.close();
            logger.info("===文件写入完成==");
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            String base64Str = TemplateDownUtils.fileToBase64(filePass);
            logger.info("==导出的文件=="+base64Str);
            response.getWriter().write(base64Str);
        } catch (Exception e) {
            throw new Exception("导出失败：失败原因："+ e.getMessage());
        }
        xssfWorkbook.close();
    }
}
